package com.ctbu.web;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import com.ctbu.entity.LoanProduct;
import com.ctbu.entity.LoanProductType;
import com.ctbu.entity.UserInfo;
import com.ctbu.service.LoanProductService;
import com.ctbu.tools.HttpStatusEnum;
import com.ctbu.tools.ResponseResult;
import com.github.pagehelper.PageInfo;

import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;

/**
 * <p>
 * 贷款产品表 前端控制器
 * </p>
 *
 * @author lli
 * @since 2024年06月18日
 */
@RestController
@RequestMapping("/loanProduct")
public class LoanProductController {
    @Autowired
    private LoanProductService loanProductService;


    /**
     * 分页查询 含快捷查询
     * @param pageNum 当前页默认1
     * @param pageSize  每页大小默认5
     * @return
     */
    @GetMapping
    public ResponseResult<Object> list(
            @RequestParam(value = "pageNum",required = false,defaultValue = "1") int pageNum,
            @RequestParam(value = "pageSize",required = false,defaultValue = "5") int pageSize,
            @RequestParam(value = "productName",required = false,defaultValue = "") String productName,
            @RequestParam(value = "interestRate",required = false,defaultValue = "") String interestRate
    ){
        return loanProductService.selectList(pageNum,pageSize,productName,interestRate);

    }

    /**
     * post:增加  put:修改 delete:删除 get:查询
     */

    @GetMapping("/{id}")
    public ResponseResult<LoanProduct> queryLoanProductById(@PathVariable String id){
        LoanProduct loanProduct=loanProductService.getById(id);
        return ResponseResult.success(loanProduct);
    }

    /**
     * @param loanProduct
     * @return
     * @RequestBody 接收前端传递的JSON数据的类型
     */
    @PostMapping
    public ResponseResult<Boolean> save(@RequestBody LoanProduct loanProduct){
        boolean b=loanProductService.save(loanProduct);
        if(b){
            return ResponseResult.success(b,"增加产品成功");
        }
        return ResponseResult.error(HttpStatusEnum.INTERNAL_SERVER_ERROR,"增加产品失败");
    }

    @PutMapping
    public ResponseResult<Boolean> update(@RequestBody LoanProduct loanProduct){
        boolean b=loanProductService.updateById(loanProduct);
        if(b){
            return ResponseResult.success(b,"修改产品成功");
        }
        return ResponseResult.error(HttpStatusEnum.INTERNAL_SERVER_ERROR,"修改产品失败");
    }

    @DeleteMapping("/{id}")
    public ResponseResult<Boolean> delete(@PathVariable String id){
        boolean b=loanProductService.removeById(id);
        if(b){
            return ResponseResult.success(b,"删除产品成功");
        }
        return ResponseResult.error(HttpStatusEnum.INTERNAL_SERVER_ERROR,"删除产品失败");
    }

    /**
     * 查询所有数据（增加或修改显示信息使用）
     * @return
     */
    @GetMapping("/queryAll")
    public ResponseResult<Object> queryAll(){
        List<LoanProduct> list = loanProductService.list();
        return ResponseResult.success(list,"查询成功");

    }


    /**
     * 导出数据
     */
    @GetMapping("exportExcel")
    public void exportExcel(
            @RequestParam(value = "pageNum",required = false,defaultValue = "1") int pageNum,
            @RequestParam(value = "pageSize",required = false,defaultValue = "5") int pageSize,
            @RequestParam(value = "productName",required = false,defaultValue = "") String productName,
            @RequestParam(value = "interestRate",required = false,defaultValue = "") String interestRate,
            HttpServletResponse response
    ) throws Exception {

        ResponseResult<Object>responseResult=loanProductService.selectList(pageNum,pageSize,productName,interestRate);
        PageInfo<LoanProduct> pageInfo=(PageInfo<LoanProduct>)responseResult.getData();
        //获取查询的数据
        List<LoanProduct> list=pageInfo.getList();
        //导出工作
        // 设置响应头
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        // 设置防止中文名乱码
        String filename = URLEncoder.encode("销售数据", "utf-8");
        // 文件下载方式(附件下载还是在当前浏览器打开)
        response.setHeader("Content-disposition", "attachment;filename=" + filename + ".xlsx");
        //导出
        Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams("贷款产品信息", "第一页"),
                LoanProduct.class, list);
        //导出流信息到浏览器
                workbook.write(response.getOutputStream());
        //释放资源
        workbook.close();
    }

    /*
     * 导入数据
     * */
    @PostMapping("/importExcel")
    public ResponseResult<Object> importExcel(MultipartFile file){
        //判断上传文件是否为空
        if (file.isEmpty()){
            return ResponseResult.error(HttpStatusEnum.INTERNAL_SERVER_ERROR,"上传文件为空");
        }
        //判断格式是否错误
        String xls = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
        String xlsx = "application/vnd.ms-excel";
        if (!xls.equals(file.getContentType())&&!xlsx.equals(file.getContentType())){
            return ResponseResult.error(HttpStatusEnum.INTERNAL_SERVER_ERROR,"上传文件格式错误");
        }
        //设置导入对象
        ImportParams importParams = new ImportParams();
        //读取第几个sheet
        importParams.setStartSheetIndex(0);
        //每次读取几个sheet
        importParams.setSheetNum(1);
        //标题占几行
        importParams.setTitleRows(1);
        //头部占几行
        importParams.setHeadRows(1);
        try {
            //生成导入excel对象
            List<LoanProduct> list = ExcelImportUtil.importExcel(file.getInputStream(),LoanProduct.class,importParams);
            //批量增加
            loanProductService.saveBatch(list);
            return ResponseResult.success(true,"数据导入成功");
        }catch (Exception e){
            e.printStackTrace();
            return ResponseResult.error(HttpStatusEnum.INTERNAL_SERVER_ERROR,"上传数据异常");
        }
    }



}
